var go = function(){
	
	//trata a acao do botao apagar
	$('[id=btnSalvar]').bind('click', function(){
		
		//funcao de callback para a acao de salvar/atualizar
		var callback = function(data){
			colocarMensagemSucesso(data.text);
			if(data.status == 'success'){
				dwr.util.setValues({'id':null, 'id_descricao':null, 'id_yaml':null});
			}
		};
		
		var id = $('[id=id]').val();
		var descricao = $('[id=id_descricao]').val();
		var yaml = $('[id=id_yaml]').val();
		if(id != null && id != ''){
			ModeloService.atualizaModelo({'id':id, 'descricao':descricao, 'yaml':yaml}, callback);
		}else{
			ModeloService.salvarNovoModelo({
				'id': id,
				'descricao': descricao,
				'yaml': yaml
			}, callback);
		}
	});
	
	var params = getQueryString();
	if(params != null && params.id != null){
		ModeloService.loadModelo(params.id, function(data){
			dwr.util.setValues(data.content);
		});
	}
	
	//trata o botao "apagar"
	if(params == null || params.id == ''){
		$('[id=btnApagar]').hide();
	}else{
		$('[id=btnApagar]').show();
		//trata a acao do botão
		$('[id=btnApagar]').bind('click', function(){
			var id = $('[id=id]').val();
			var decisao = confirm('Deseja realmente apagar o modelo?');
			if(decisao){
				ModeloService.removerModelo(id, function(data){
					dwr.util.setValue('message-panel', data.text);
					if(data.type == 'success'){
						dwr.util.setValues({'id':null, 'id_descricao':null, 'id_yaml':null});
					}
				});
			}
		});
	}
	
	
	if(!params){
		jQuery("#bntComb").hide();
	}else{
		
		jQuery("#btnComb").click(function(event){
		
			var tableComb = jQuery("<table></table>");
			var buttonNovo = jQuery("<input type='button'></input>");
			buttonNovo.css("float","right");
			buttonNovo.val("Novo");
			buttonNovo.click(function(){
				window.location = "/geco-web/combinacoes/combinacao.html?idModelo="+params.id;
			});
			
			var dialogTemplate = jQuery("<div></div>").attr("title","Combinações").css("text-align","center");
			dialogTemplate.appendTo(document.body);
			dialogTemplate.append(tableComb);
			dialogTemplate.append(buttonNovo);
			dialogTemplate.dialog({
				width: 600,
				modal:true,
				close: function(event, ui){
					dialogTemplate.remove();
				}
			});
			
			tableComb.jqGrid( {
				mtype: "POST",
				url : '/geco-web/combinacao/buscar.do?idModelo='+params.id,
				datatype : "json",
				autowidth: true,
				colNames : [ 'Código', 'Descrição'],
				colModel : [ {
					name : 'id',
					index : 'id',
					width : 80
				}, {
					name : 'descricao',
					index : 'descricao',
					width : 250
				}],
				ondblClickRow: function(rowid,iRow,iCol){
					var obj = tableComb.getRowData(rowid);
					window.location = "/geco-web/combinacoes/combinacao.html?idCombinacao="+obj.id;
				}
			}); 				
		
		});
	}	
	
};

jQuery(go);